//
//  LXCarSettingViewController.m
//  INMOTION_CustomMadeProject
//
//  Created by cjg on 2021/3/23.
//  Copyright © 2021 cjg. All rights reserved.
//

#import "LXCarSettingViewController.h"
#import "IMTConfig.h"
#import "IMTCANManager.h"
#import "IMTUnitHelper.h"
#import "IMTCarManager.h"
#import "NSObject+HUD.h"
#import "KSLanguageManager.h"
#import "L9_CarModel.h"
#import "NewFirmwareUpdateViewController.h"
#import "DetectionViewController.h"
#import "L9CorrectionViewController.h"
#import "IMTAboutCarViewController.h"
#import "RidingAssistanceViewController.h"
#import "LXCarBlePasswordViewController.h"
#import "LXCustom.h"
#import "AppTypeTool.h"

@interface LXCarSettingViewController ()

@property (weak, nonatomic) IBOutlet UILabel *closeCarLB;
@property (weak, nonatomic) IBOutlet UISwitch *closeCarSwitch;
@property (weak, nonatomic) IBOutlet UILabel *lockCarLB;
@property (weak, nonatomic) IBOutlet UISwitch *lockCarSwitch;
@property (weak, nonatomic) IBOutlet UILabel *searchLB;
@property (weak, nonatomic) IBOutlet UISlider *maxSpeedSlider;
@property (weak, nonatomic) IBOutlet UILabel *maxSpeedNumLB;
@property (weak, nonatomic) IBOutlet UILabel *maxSpeedUintLB;
@property (weak, nonatomic) IBOutlet UISlider *speedUpSlider;
@property (weak, nonatomic) IBOutlet UILabel *speedUpValueLB;
@property (weak, nonatomic) IBOutlet UISlider *speedDownSlider;
@property (weak, nonatomic) IBOutlet UILabel *speedDownValueLB;
@property (weak, nonatomic) IBOutlet UILabel *cruiseTitleLB;
@property (weak, nonatomic) IBOutlet UISwitch *cruiseSwitch;
@property (weak, nonatomic) IBOutlet UILabel *lightTitleLB;
@property (weak, nonatomic) IBOutlet UISwitch *lightSwitch;
@property (weak, nonatomic) IBOutlet UILabel *ambientLightLB;
@property (weak, nonatomic) IBOutlet UISwitch *ambientLightSwitch;
@property (weak, nonatomic) IBOutlet UILabel *turnLightlb;
@property (weak, nonatomic) IBOutlet UISwitch *turnLightSwitch;
@property (weak, nonatomic) IBOutlet UILabel *zeroSpeedStartLB;
@property (weak, nonatomic) IBOutlet UISwitch *zeroSpeedStartSwitch;
@property (weak, nonatomic) IBOutlet UISegmentedControl *speedUnitSegControl;
@property (weak, nonatomic) IBOutlet UISegmentedControl *rideModeSegControl;
@property (weak, nonatomic) IBOutlet UILabel *l5RideModeTipLB;
@property (weak, nonatomic) IBOutlet UISegmentedControl *l5RideModeSegControl;
@property (weak, nonatomic) IBOutlet UILabel *rideModeTipLB;
@property (weak, nonatomic) IBOutlet UILabel *handelCheckLB;
@property (weak, nonatomic) IBOutlet UILabel *firmwareUpdateLB;
@property (weak, nonatomic) IBOutlet UILabel *speedLimitLB;
@property (weak, nonatomic) IBOutlet UISwitch *speedLimitSwitch;
@property (weak, nonatomic) IBOutlet UILabel *ridingAssistanceLB;
@property (weak, nonatomic) IBOutlet UILabel *aboutCarLB;
@property (weak, nonatomic) IBOutlet UILabel *diagnoseLB;
@property (weak, nonatomic) IBOutlet UILabel *carPasswordLB;


@property (nonatomic, strong) NSMutableArray *sections;


@property (nonatomic, strong) NSTimer *timer;

@end

@implementation LXCarSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configDetailView];
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"nav_back_white"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] style:(UIBarButtonItemStylePlain) target:self action:@selector(backAction)];
    self.navigationItem.leftBarButtonItem = left;
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    // 获取本地密码
    [self.carModel.l9_CarModel loadLocalCarBlePassword];
    
    
    // 定时更新骑行模式状态
    if (self.timer) {
        [self.timer invalidate];
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(reloadRideModel:) userInfo:nil repeats:YES];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)reloadRideModel:(NSTimer *)timer {
    NSLog(@"--- reloadData ---");
    // C1车型定时更新骑行模式状态
    // 读取设置项状态
    [self.carModel.l9_CarModel getDataWithCmdType:(L9_CarModelCmdTypeComplexSetting) isRepeat:YES compleBlock:^(NSError *error, NSData *responseData) {
        NSLog(@"获取所有设置项状态的结果 ================= 🌞 %@ -- %@ -- %d",error,responseData,self.carModel.l9_CarModel.lockSwitch);
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionRideModel] withRowAnimation:UITableViewRowAnimationNone];
    }];
}


- (void)backAction {
    [self dismissHUD];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)configDetailView {
    
    self.closeCarSwitch.onTintColor = [AppTypeTool getThemeColor];
    self.lockCarSwitch.onTintColor = [AppTypeTool getThemeColor];
    self.lightSwitch.onTintColor = [AppTypeTool getThemeColor];
    self.speedLimitSwitch.onTintColor = [AppTypeTool getThemeColor];
        
    [[IMTCANManager sharedInstance] clearMessages];
    [self getStatusData];
    [self configL9View];
    
    // 国际化字符
    [self localizedString];
    [self initViewStyle];
}

// 国际化字符串
- (void)localizedString {
     self.title = IMTNewCarLocalizedString(@"dialog_go_to_settings");
     self.lockCarLB.text = IMTNewCarLocalizedString(@"fragment_car_status_lock");
     self.closeCarLB.text = @"关机";
     self.zeroSpeedStartLB.text = @"零速启动";
     self.cruiseTitleLB.text = IMTNewCarLocalizedString(@"car_feature_cruise");
     self.lightTitleLB.text = IMTNewCarLocalizedString(@"fragment_car_status_light");
     self.ambientLightLB.text = IMTNewCarLocalizedString(@"car_feature_light_effect");
     self.turnLightlb.text = IMTNewCarLocalizedString(@"car_feature_auto_turn_signal");
     self.handelCheckLB.text = IMTNewCarLocalizedString(@"car_feature_vehicle_calibration");
     self.firmwareUpdateLB.text = IMTNewCarLocalizedString(@"car_feature_fw_upgrade");
     self.ridingAssistanceLB.text = IMTNewCarLocalizedString(@"car_feature_riding_assist");
    self.aboutCarLB.text = IMTNewCarLocalizedString(@"car_feature_about_car");
    self.diagnoseLB.text = IMTNewCarLocalizedString(@"fragment_car_settings_diagnose");
    [self.speedUnitSegControl setTitle:IMTNewCarLocalizedString(@"car_feature_metric_metric") forSegmentAtIndex:0];
    [self.speedUnitSegControl setTitle:IMTNewCarLocalizedString(@"car_feature_metric_imperial") forSegmentAtIndex:1];
    self.carPasswordLB.text = IMTNewCarLocalizedString(@"activity_change_bt_pwd_title");

     NSString *str = @"";
     if (IMTUnitHelper.useMetricUnit) {
         str = @"25km/h";
     }else {
         str = @"15mph";
     }
     self.speedLimitLB.text = [NSString stringWithFormat:IMTNewCarLocalizedString(@"allow_bigger_speed_limit_state"),str];
}

// 初始化样式
- (void)initViewStyle {
    self.zeroSpeedStartSwitch.onTintColor = [AppTypeTool getThemeColor];
    self.cruiseSwitch.onTintColor = [AppTypeTool getThemeColor];
    if (@available(iOS 13.0, *)) {
        self.speedUnitSegControl.selectedSegmentTintColor = [AppTypeTool getThemeColor];
        self.rideModeSegControl.selectedSegmentTintColor = [AppTypeTool getThemeColor];
        self.l5RideModeSegControl.selectedSegmentTintColor = [AppTypeTool getThemeColor];
        
    } else {
        self.speedUnitSegControl.tintColor = [AppTypeTool getThemeColor];
        self.rideModeSegControl.tintColor = [AppTypeTool getThemeColor];
        self.l5RideModeSegControl.tintColor = [AppTypeTool getThemeColor];
    }
    
//    [self.rideModeSegControl setImage:[UIImage imageNamed:@"rideModel_yes.png"] forSegmentAtIndex:3];
//    [self.l5RideModeSegControl setImage:[UIImage imageNamed:@"rideModel_yes.png"] forSegmentAtIndex:3];
    // 选中和常态字体样式
    [self.speedUnitSegControl setTitleTextAttributes:@{NSForegroundColorAttributeName: [AppTypeTool getThemeColor], NSFontAttributeName: [UIFont systemFontOfSize:17]} forState:UIControlStateNormal];
    [self.speedUnitSegControl setTitleTextAttributes:@{NSForegroundColorAttributeName: UIColor.whiteColor, NSFontAttributeName: [UIFont systemFontOfSize:17]} forState:UIControlStateSelected];
    
    [self.rideModeSegControl setTitleTextAttributes:@{NSForegroundColorAttributeName: [AppTypeTool getThemeColor], NSFontAttributeName: [UIFont systemFontOfSize:17]} forState:UIControlStateNormal];
    [self.rideModeSegControl setTitleTextAttributes:@{NSForegroundColorAttributeName: UIColor.whiteColor, NSFontAttributeName: [UIFont systemFontOfSize:17]} forState:UIControlStateSelected];
    [self.rideModeSegControl setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor darkGrayColor], NSFontAttributeName: [UIFont systemFontOfSize:17]} forState:UIControlStateDisabled];
    [self.l5RideModeSegControl setTitleTextAttributes:@{NSForegroundColorAttributeName: [AppTypeTool getThemeColor], NSFontAttributeName: [UIFont systemFontOfSize:17]} forState:UIControlStateNormal];
    [self.l5RideModeSegControl setTitleTextAttributes:@{NSForegroundColorAttributeName: UIColor.whiteColor, NSFontAttributeName: [UIFont systemFontOfSize:17]} forState:UIControlStateSelected];
    [self.l5RideModeSegControl setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor darkGrayColor], NSFontAttributeName: [UIFont systemFontOfSize:17]} forState:UIControlStateDisabled];
    
    BOOL enabled = [KSBLEManager sharedManager].state == KSBLEManagerStateSubscribed;
    self.tableView.allowsSelection = enabled;
    [self.tableView reloadData];
}

#pragma mark - 根据车型配置界面
- (void)getStatusData {
    
    [self showProgressHUDWithText:nil];
    if (IMTCarSeriesLorin(self.carModel.carType)) {
        [self fetchL9Data];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self dismissHUD];
    });
}

- (void)fetchL9Data {
    if([KSBLEManager sharedManager].state == KSBLEManagerStateSubscribed) {
        // 读取设置项状态
        [self.carModel.l9_CarModel getDataWithCmdType:(L9_CarModelCmdTypeComplexSetting) isRepeat:YES compleBlock:^(NSError *error, NSData *responseData) {
            NSLog(@"获取所有设置项状态的结果 ================= 🌞 %@ -- %@ -- %d",error,responseData,self.carModel.l9_CarModel.lockSwitch);
            [self.tableView reloadData];
        }];
        // 读取当前固件版本号
        [self.carModel.l9_CarModel getCarVersionSuccessBlock:^{
            NSLog(@"获取固件版本号的结果 ================= 🌞🌞🌞🌞  -- %@",self.carModel.l9_CarModel.carVersion);
        } failBlock:^(NSError *error) {
            NSLog(@"获取固件版本号的结果 ================= 🌞🌞🌞  -- 失败");
        }];
        // 获取sn
        [self.carModel.l9_CarModel getCarSNWithCompleBlock:^(NSError *error, NSData *responseData) {
            NSLog(@"获取车辆sn的结果 ================= 🌞🌞  %@ == %@",error,responseData);
        }];
    }
}

- (void)configL9View {
    if (IMTCarSeriesL5(self.carModel.carType)) {
        self.sections = [NSMutableArray arrayWithArray:@[
            @(IMTNewL9CarDetailSectionLock),
            @(IMTNewL9CarDetailSectionCruiseControl),
            @(IMTNewL9CarDetailSectionSpeedUint),
            @(IMTNewL9CarDetailSectionL5RideModel),
            @(IMTNewL9CarDetailSectionLight),
            @(IMTNewL9CarDetailSectionCalibration),
            @(IMTNewL9CarDetailSectionFirmwareUpdate),
            @(IMTNewL9CarDetailSectionAboutCar),
            @(IMTNewL9CarDetailSectionDiagnose)
        ]];
    }else {
        
        self.sections = [NSMutableArray arrayWithArray:@[
            @(IMTNewL9CarDetailSectionLock),
            @(IMTNewL9CarDetailSectionSpeedUint),
            @(IMTNewL9CarDetailSectionRideModel),
//            @(IMTNewL9CarDetailSectionLight),
//            @(IMTNewL9CarDetailSectionAmbientLight),
//            @(IMTNewL9CarDetailSectionTurnLight),
//            @(IMTNewL9CarDetailSectionCruiseControl),
//            @(IMTNewL9CarDetailSectionCalibration),
//            @(IMTNewL9CarDetailSectionRidingAssistance),
            @(IMTNewL9CarDetailSectionFirmwareUpdate),
            @(IMTNewL9CarDetailSectionAboutCar),
            @(IMTNewL9CarDetailSectionDiagnose)
        ]];
        
        if (self.carModel.l9_CarModel.maxSpeed <= 25) {
//            [self.sections addObject:@(IMTNewL9CarDetailSectionSpeedLimitSwitch)];
        }
        
        if ([LXCustom sharedCustom].needPassword) {
            [self.sections addObject:@(IMTNewL9CarDetailSectionCarPassword)];
        }
        
    }
    self.maxSpeedSlider.maximumValue = 30;
    self.maxSpeedSlider.minimumValue = 5;
}

#pragma mark --- L9设置项
// 判断车辆是否存在密码
- (void)checkCarIsHasPassword:(void(^)(BOOL))block {
    
    if (self.carModel.blePassword) { // 本地存在密码
        if (block) {
            block(YES);
        }
    }else { // 本地不存在密码
        [self.carModel.l9_CarModel checkBlePasswordWithPassword:nil successBlock:^{
            NSLog(@" ========== 车辆不存在密码");
            if (block) {
                block(NO);
            }
        } failBlock:^(NSError *error) {
            NSLog(@"========== 车辆存在密码");
            if (block) {
                block(YES);
            }
        }];
    }
}

// 验证密码
- (void)checkCarPasswordWithPassword:(NSString *)password block:(void(^)(BOOL))block{
    [self.carModel.l9_CarModel checkBlePasswordWithPassword:[IMFunction strToAscll:password] successBlock:^{
        NSLog(@" ========== 车辆密码验证通过");
        self.carModel.l9_CarModel.blePassword = password;
        [self.carModel.l9_CarModel saveCarBlePassword];
        if (block) {
            block(YES);
        }
    } failBlock:^(NSError *error) {
        NSLog(@"========== 车辆密码不通过");
        if (block) {
            block(NO);
        }
    }];
}

// 安全连接
- (void)safeConnect:(NSString *)password {
    WS(weakSelf)
    [self.carModel.l9_CarModel getSafeChannelWithCompleBlock:^(NSError *error, NSData *responseData) {
        if (error == nil && weakSelf.carModel.l9_CarModel.randomCode) {
            [weakSelf.carModel.l9_CarModel setSafePasswordWithPassword:weakSelf.carModel.l9_CarModel.randomCode successBlock:^{
                [weakSelf writePasswordToCar:password];
            } failBlock:^(NSError *error) {
                [weakSelf showErrorHUDWithText:IMTNewCarLocalizedString(@"setting_failed")];
                return;
            }];
        }else {
            [weakSelf showErrorHUDWithText:IMTNewCarLocalizedString(@"setting_failed")];
            return;
        }
    }];
}

// 写入密码
- (void)writePasswordToCar:(NSString *)password {
    NSData *param = [IMFunction strToAscll:password];
    [self.carModel.l9_CarModel writeBlePasswordWithPassword:param successBlock:^{
        self.carModel.l9_CarModel.blePassword = password;
        [self.carModel.l9_CarModel saveCarBlePassword];
        [self showSuccessHUDWithText:IMTNewCarLocalizedString(@"prompt_change_bt_pwd_successfully")];
        [self.navigationController popViewControllerAnimated:YES];
    } failBlock:^(NSError *error) {
        [self showErrorHUDWithText:IMTNewCarLocalizedString(@"prompt_change_bt_pwd_failed")];
    }];
}

- (void)showInputPasswordWithType:(NSInteger)type isLock:(uint8_t)lockValue {
    NSString * title = @"";
    if (type == 0) {
        title = IMTNewCarLocalizedString(@"dialog_input_pwd_hint");
    }
    if (type == 1) {
        title = IMTNewCarLocalizedString(@"prompt_goto_set_pwd");
    }

    UIAlertController *ac = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:(UIAlertControllerStyleAlert)];
    [ac addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = IMTNewCarLocalizedString(@"dialog_input_pwd_hint");
        textField.keyboardType = UIKeyboardTypeNumberPad;
        textField.secureTextEntry = YES;
    }];
    if (type == 1) {
        [ac addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.placeholder = IMTNewCarLocalizedString(@"activity_change_bt_pwd_hint_confirm_new_pwd");
            textField.keyboardType = UIKeyboardTypeNumberPad;
            textField.secureTextEntry = YES;
        }];
    }
    UIAlertAction *confirm = [UIAlertAction actionWithTitle:IMTNewCarLocalizedString(@"activity_change_bt_pwd_btn_text") style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        UITextField *psField = ac.textFields[0];
        if (type == 0) {
            [self checkCarPasswordWithPassword:psField.text block:^(BOOL isok) {
                if (isok) {
                    [self showSuccessHUDWithText:IMTNewCarLocalizedString(@"setting_success")];
                    // 解锁车辆
                    [self setCarLockWithValue:lockValue];
                }else {
                    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionLock] withRowAnimation:UITableViewRowAnimationNone];
                    [self showErrorHUDWithText:IMTNewCarLocalizedString(@"setting_failed")];
                }
            }];
        }
        if (type == 1) {
            UITextField *surepsField = ac.textFields[1];
            if ([psField.text isEqualToString:surepsField.text]) {
                [self safeConnect:psField.text];
            }else {
                [self showErrorHUDWithText:IMTNewCarLocalizedString(@"prompt_change_bt_pwd_confirm_pwd_not_match")];
            }
        }

    }];
    UIAlertAction *Cancel = [UIAlertAction actionWithTitle:IMTNewCarLocalizedString(@"dialog_cancel") style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        if (type == 0) {
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionLock] withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
    [ac addAction:confirm];
    [ac addAction:Cancel];
    [self presentViewController:ac animated:YES completion:nil];
}

// 关机
- (IBAction)closeCar:(UISwitch *)sender {
    [self showProgressHUDWithText:nil];
    [self.carModel.l9_CarModel writeDataWithL9CmdType:(L9_CarModelCmdTypeClooseCar) dataParam:nil successBlock:^{
        [self showSuccessHUDWithText:IMTNewCarLocalizedString(@"setting_success")];
    } failBlock:^(NSError *error) {
        [self showErrorHUDWithText:[NSString stringWithFormat:@"%@(%ld)",IMTNewCarLocalizedString(@"setting_failed"),(long)error.code]];
    }];
}

// 锁车
- (IBAction)lockCar:(UISwitch *)sender {
    
    if (![LXCustom sharedCustom].needPassword) {
        uint8_t value = sender.on;
        [self setCarLockWithValue:value];
    } else {
        [self checkCarIsHasPassword:^(BOOL isHas) {
            if (isHas) {
                if (self.carModel.blePassword) {
                    // 使用本地密码验证
                    NSLog(@"==================- 使用本地密码验证");
                    [self checkCarPasswordWithPassword:self.carModel.blePassword block:^(BOOL isok) {
                        if (isok) {
                            uint8_t value = sender.on;
                            [self setCarLockWithValue:value];
                        }else {
                            // 弹框提示用户输入密码验证
                            NSLog(@"==================- 弹框提示用户输入密码验证");
                            uint8_t value = sender.on;
                            [self showInputPasswordWithType:0 isLock:value];
                        }
                    }];
                }else {
                    // 弹框提示用户输入密码验证
                    NSLog(@"==================- 弹框提示用户输入密码验证");
                    uint8_t value = sender.on;
                    [self showInputPasswordWithType:0 isLock:value];
                }

            }else {
                [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionLock] withRowAnimation:UITableViewRowAnimationNone];
                // 提示输入蓝牙密码设置
                NSLog(@"==================- 还未设置蓝牙密码");
                [self showInputPasswordWithType:1 isLock:0];
            }
        }];
    }
}

//锁车
- (void)setCarLockWithValue:(uint8_t)value {
    NSString *mes = nil;
    NSString *successStr = nil;
    NSString *failStr = nil;
    if (value) {
        mes = IMTNewCarLocalizedString(@"prompt_locking");
        successStr = IMTNewCarLocalizedString(@"prompt_lock_success");
        failStr = IMTNewCarLocalizedString(@"prompt_lock_failed");
    }else {
        mes = IMTNewCarLocalizedString(@"prompt_unlocking");
        successStr = IMTNewCarLocalizedString(@"prompt_unlock_success");
        failStr = IMTNewCarLocalizedString(@"prompt_unlock_failed");
    }

    [self showProgressHUDWithText:mes];
    
    WS(weakSelf)
    [self.carModel.l9_CarModel writeDataWithCmdType:(L9_CarModelCmdTypeLockCar) uint8Param:value successBlock:^{
        self.carModel.l9_CarModel.lockSwitch = value;
        [weakSelf showSuccessHUDWithText:successStr];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionLock] withRowAnimation:UITableViewRowAnimationNone];
    } failBlock:^(NSError *error) {
        [weakSelf showErrorHUDWithText:failStr];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionLock] withRowAnimation:UITableViewRowAnimationNone];
    }];
}

// 限速
- (IBAction)maxSpeedChange:(UISlider *)sender {
    self.maxSpeedNumLB.text = [NSString stringWithFormat:@"%.f",sender.value];
}
- (IBAction)maxSpeedEnd:(UISlider *)sender {
    [self showProgressHUDWithText:nil];
    WS(weakSelf)
    uint16_t value = (uint16_t)(sender.value * 100);
    [self.carModel.l9_CarModel writeDataWithCmdType:(L9_CarModelCmdTypeSetMaxSpeed) uint16Param:value successBlock:^{
        L9_SettingParams param = self.carModel.l9_CarModel.settingParams;
        param.limit_speed = value;
        self.carModel.l9_CarModel.settingParams = param;
        [weakSelf showSuccessHUDWithText:IMTNewCarLocalizedString(@"setting_success")];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionMaxSpeed] withRowAnimation:UITableViewRowAnimationNone];
    } failBlock:^(NSError *error) {
        [weakSelf showErrorHUDWithText:[NSString stringWithFormat:@"%@(%ld)",IMTNewCarLocalizedString(@"setting_failed"),(long)error.code]];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionMaxSpeed] withRowAnimation:UITableViewRowAnimationNone];
    }];
}

// 加速力度
- (IBAction)speedUpIntensityChange:(UISlider *)sender {
    self.speedUpValueLB.text = [NSString stringWithFormat:@"%.f",sender.value];
}
- (IBAction)speedUpIntensityEnd:(UISlider *)sender {
    [self showProgressHUDWithText:nil];
    WS(weakSelf)
    uint8_t value = (uint8_t)sender.value;
    [self.carModel.l9_CarModel writeDataWithCmdType:(L9_CarModelCmdTypeAccelerationForce) uint8Param:value successBlock:^{
        L9_SettingParams param = self.carModel.l9_CarModel.settingParams;
        param.accelerate_force = value;
        self.carModel.l9_CarModel.settingParams = param;
        [weakSelf showSuccessHUDWithText:IMTNewCarLocalizedString(@"setting_success")];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionSpeedUpIntensity] withRowAnimation:UITableViewRowAnimationNone];
    } failBlock:^(NSError *error) {
        [weakSelf showErrorHUDWithText:[NSString stringWithFormat:@"%@(%ld)",IMTNewCarLocalizedString(@"setting_failed"),(long)error.code]];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionSpeedUpIntensity] withRowAnimation:UITableViewRowAnimationNone];
    }];
}

// 减速力度
- (IBAction)speedDownIntensityChange:(UISlider *)sender {
    self.speedDownValueLB.text = [NSString stringWithFormat:@"%.f",sender.value];
}
- (IBAction)speedDownIntensityEnd:(UISlider *)sender {
    [self showProgressHUDWithText:nil];
    WS(weakSelf)
    uint8_t value = (uint8_t)sender.value;
    [self.carModel.l9_CarModel writeDataWithCmdType:(L9_CarModelCmdTypeBrakeForce) uint8Param:value successBlock:^{
        L9_SettingParams param = self.carModel.l9_CarModel.settingParams;
        param.brake_force = value;
        self.carModel.l9_CarModel.settingParams = param;
        [weakSelf showSuccessHUDWithText:IMTNewCarLocalizedString(@"setting_success")];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionSpeedDownIntensity] withRowAnimation:UITableViewRowAnimationNone];
    } failBlock:^(NSError *error) {
        [weakSelf showErrorHUDWithText:[NSString stringWithFormat:@"%@(%ld)",IMTNewCarLocalizedString(@"setting_failed"),(long)error.code]];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionSpeedDownIntensity] withRowAnimation:UITableViewRowAnimationNone];
    }];
}

// 自动巡航
- (IBAction)cruiseSwitch:(UISwitch *)sender {
    [self showProgressHUDWithText:nil];
    WS(weakSelf)
    uint8_t value = (uint8_t)sender.on;
    [self.carModel.l9_CarModel writeDataWithCmdType:(L9_CarModelCmdTypeAutomaticCruise) uint8Param:value successBlock:^{
        L9_SettingParams param = self.carModel.l9_CarModel.settingParams;
        param.auto_cruise = value == 1;
        self.carModel.l9_CarModel.settingParams = param;
        [weakSelf showSuccessHUDWithText:IMTNewCarLocalizedString(@"setting_success")];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionCruiseControl] withRowAnimation:UITableViewRowAnimationNone];
    } failBlock:^(NSError *error) {
        [weakSelf showErrorHUDWithText:[NSString stringWithFormat:@"%@(%ld)",IMTNewCarLocalizedString(@"setting_failed"),(long)error.code]];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionCruiseControl] withRowAnimation:UITableViewRowAnimationNone];
    }];
}

// 前灯开关
- (IBAction)lightSwich:(UISwitch *)sender {
    
    [self showProgressHUDWithText:nil];
    WS(weakSelf)
    uint8_t value = (uint8_t)sender.on;
    [self.carModel.l9_CarModel writeDataWithCmdType:(L9_CarModelCmdTypeSetLight) uint8Param:value successBlock:^{
        weakSelf.carModel.l9_CarModel.lightSwitch = value == 1;
        [weakSelf showSuccessHUDWithText:IMTNewCarLocalizedString(@"setting_success")];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionLight] withRowAnimation:UITableViewRowAnimationNone];
    } failBlock:^(NSError *error) {
        [weakSelf showErrorHUDWithText:[NSString stringWithFormat:@"%@(%ld)",IMTNewCarLocalizedString(@"setting_failed"),(long)error.code]];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionLight] withRowAnimation:UITableViewRowAnimationNone];
    }];
}

// 氛围灯开关
- (IBAction)ambientLightSwitch:(UISwitch *)sender {
    [self showProgressHUDWithText:nil];
    WS(weakSelf)
    uint8_t value ;
    if (sender.on) {
        if (self.carModel.l9_CarModel.turnLightSwitch) {
            value = 2;
        }else {
            value = 1;
        }
    }else {
        if (self.carModel.l9_CarModel.turnLightSwitch) {
            value = 3;
        }else {
            value = 0;
        }
    }
    [self.carModel.l9_CarModel writeDataWithCmdType:(L9_CarModelCmdTypeSettingAmbientLightSwitch) uint8Param:value successBlock:^{
        weakSelf.carModel.l9_CarModel.ambientLightSwitch = (value == 1) || (value == 2);
        [weakSelf showSuccessHUDWithText:IMTNewCarLocalizedString(@"setting_success")];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionAmbientLight] withRowAnimation:UITableViewRowAnimationNone];
    } failBlock:^(NSError *error) {
        [weakSelf showErrorHUDWithText:[NSString stringWithFormat:@"%@(%ld)",IMTNewCarLocalizedString(@"setting_failed"),(long)error.code]];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionAmbientLight] withRowAnimation:UITableViewRowAnimationNone];
    }];
}

// 转向灯开关
- (IBAction)turnLightSwitch:(UISwitch *)sender {
    [self showProgressHUDWithText:nil];
    WS(weakSelf)
    uint8_t value ;
    if (sender.on) {
        if (self.carModel.l9_CarModel.ambientLightSwitch) {
            value = 2;
        }else {
            value = 3;
        }
    }else {
        if (self.carModel.l9_CarModel.ambientLightSwitch) {
            value = 1;
        }else {
            value = 0;
        }
    }
    [self.carModel.l9_CarModel writeDataWithCmdType:(L9_CarModelCmdTypeSettingAmbientLightSwitch) uint8Param:value successBlock:^{
        weakSelf.carModel.l9_CarModel.turnLightSwitch = (value == 3) || (value == 2);
        [weakSelf showSuccessHUDWithText:IMTNewCarLocalizedString(@"setting_success")];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionTurnLight] withRowAnimation:UITableViewRowAnimationNone];
    } failBlock:^(NSError *error) {
        [weakSelf showErrorHUDWithText:[NSString stringWithFormat:@"%@(%ld)",IMTNewCarLocalizedString(@"setting_failed"),(long)error.code]];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionTurnLight] withRowAnimation:UITableViewRowAnimationNone];
    }];
}

// 零速启动
- (IBAction)zeroSpeedStartSwitch:(UISwitch *)sender {
    [self showProgressHUDWithText:nil];
    WS(weakSelf)
    uint8_t value = (uint8_t)sender.on;
    [self.carModel.l9_CarModel writeDataWithCmdType:(L9_CarModelCmdTypeZeroSpeedStart) uint8Param:value successBlock:^{
        L9_SettingParams param = self.carModel.l9_CarModel.settingParams;
        param.zero_startup = value;
        self.carModel.l9_CarModel.settingParams = param;
        [weakSelf showSuccessHUDWithText:IMTNewCarLocalizedString(@"setting_success")];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionZeroSpeedStart] withRowAnimation:UITableViewRowAnimationNone];
    } failBlock:^(NSError *error) {
        if (error.code == 5) {
            [weakSelf showErrorHUDWithText:IMTNewCarLocalizedString(@"Please try again after releasing the throttle.")];
        }else {
            [weakSelf showErrorHUDWithText:[NSString stringWithFormat:@"%@(%ld)",IMTNewCarLocalizedString(@"setting_failed"),(long)error.code]];
        }
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionZeroSpeedStart] withRowAnimation:UITableViewRowAnimationNone];
    }];
}

// 速度单位
- (IBAction)speedUnitSegControl:(UISegmentedControl *)sender {
    [self showProgressHUDWithText:nil];
    WS(weakSelf)
    uint8_t value = (uint8_t)sender.selectedSegmentIndex;
    [self.carModel.l9_CarModel writeDataWithCmdType:(L9_CarModelCmdTypeSpeedUnit) uint8Param:value successBlock:^{
        L9_SettingParams param = self.carModel.l9_CarModel.settingParams;
        param.speed_unit = value;
        [IMTUnitHelper setUseMetricUnit:value == 0];
        self.carModel.l9_CarModel.settingParams = param;
        [weakSelf showSuccessHUDWithText:IMTNewCarLocalizedString(@"setting_success")];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionSpeedUint] withRowAnimation:UITableViewRowAnimationNone];
    } failBlock:^(NSError *error) {
        [weakSelf showErrorHUDWithText:[NSString stringWithFormat:@"%@(%ld)",IMTNewCarLocalizedString(@"setting_failed"),(long)error.code]];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionSpeedUint] withRowAnimation:UITableViewRowAnimationNone];
    }];
}

// 限速开关
- (IBAction)speedLimitSwitch:(UISwitch *)sender {
    if (!sender.on) {
        NSString *str = [NSString stringWithFormat:@"    %@\n    %@",IMTNewCarLocalizedString(@"prompt_disallow_bigger_speed_limit_desc"),IMTNewCarLocalizedString(@"prompt_allow_bigger_speed_limit_warning")];
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:IMTNewCarLocalizedString(@"dialog_title_warning") message:str preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *commit = [UIAlertAction actionWithTitle:IMTNewCarLocalizedString(@"activity_change_bt_pwd_btn_text") style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            uint8_t value = (uint8_t)sender.on;
            [self setSpeedLimitValue:value];
        }];
        UIAlertAction *cancle = [UIAlertAction actionWithTitle:IMTNewCarLocalizedString(@"dialog_cancel") style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionSpeedLimitSwitch] withRowAnimation:UITableViewRowAnimationNone];
        }];
        [commit setValue:kIMTDefaultOrangeColor forKey:@"titleTextColor"];
        [alertVC addAction:commit];
        [alertVC addAction:cancle];
        [self presentViewController:alertVC animated:YES completion:nil];
    }else {
        uint8_t value = (uint8_t)sender.on;
        [self setSpeedLimitValue:value];
    }
}

- (void)setSpeedLimitValue:(uint8_t)value {
    [self showProgressHUDWithText:nil];
    WS(weakSelf)
    [self.carModel.l9_CarModel writeDataWithCmdType:(L9_CarModelCmdTypeSettingSpeedLimitState) uint8Param:value successBlock:^{
        L9_SettingParams param = self.carModel.l9_CarModel.settingParams;
        param.smart_acc = value;
        weakSelf.carModel.l9_CarModel.settingParams = param;
        weakSelf.carModel.l9_CarModel.speedLimitSwitch = value == 1;
        [weakSelf showSuccessHUDWithText:IMTNewCarLocalizedString(@"setting_success")];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionSpeedLimitSwitch] withRowAnimation:UITableViewRowAnimationNone];
    } failBlock:^(NSError *error) {
        [weakSelf showErrorHUDWithText:[NSString stringWithFormat:@"%@(%ld)",IMTNewCarLocalizedString(@"setting_failed"),(long)error.code]];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionSpeedLimitSwitch] withRowAnimation:UITableViewRowAnimationNone];
    }];
}

// L5骑行模式
- (IBAction)l5RideModelSegControl:(UISegmentedControl *)sender {
    [self showProgressHUDWithText:nil];
    WS(weakSelf)
    uint8_t value = (uint8_t)sender.selectedSegmentIndex;
    
    [self.carModel.l9_CarModel writeDataWithCmdType:(L9_CarModelCmdTypeRideModel) uint8Param:value successBlock:^{
        L9_SettingParams param = self.carModel.l9_CarModel.settingParams;
        param.driver_mode = value;
        self.carModel.l9_CarModel.settingParams = param;
        [weakSelf showSuccessHUDWithText:IMTNewCarLocalizedString(@"setting_success")];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionL5RideModel] withRowAnimation:UITableViewRowAnimationNone];
    } failBlock:^(NSError *error) {
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionL5RideModel] withRowAnimation:UITableViewRowAnimationNone];
        if (error.code == 5) {
            [weakSelf showErrorHUDWithText:IMTNewCarLocalizedString(@"Please try again after releasing the throttle.")];
        }else {
            [weakSelf showErrorHUDWithText:[NSString stringWithFormat:@"%@(%ld)",IMTNewCarLocalizedString(@"setting_failed"),(long)error.code]];
        }
    }];
}

// 骑行模式
- (IBAction)rideModelSegControl:(UISegmentedControl *)sender {
    [self showProgressHUDWithText:nil];
    WS(weakSelf)
    uint8_t value = (uint8_t)sender.selectedSegmentIndex;
    
    [self.carModel.l9_CarModel writeDataWithCmdType:(L9_CarModelCmdTypeRideModel) uint8Param:value successBlock:^{
        L9_SettingParams param = self.carModel.l9_CarModel.settingParams;
        param.driver_mode = value;
        self.carModel.l9_CarModel.settingParams = param;
        [weakSelf showSuccessHUDWithText:IMTNewCarLocalizedString(@"setting_success")];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionRideModel] withRowAnimation:UITableViewRowAnimationNone];
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionSpeedLimitSwitch] withRowAnimation:UITableViewRowAnimationNone];
    } failBlock:^(NSError *error) {
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:IMTNewL9CarDetailSectionRideModel] withRowAnimation:UITableViewRowAnimationNone];
        if (error.code == 5) {
            [weakSelf showErrorHUDWithText:IMTNewCarLocalizedString(@"Please try again after releasing the throttle.")];
        }else {
            [weakSelf showErrorHUDWithText:[NSString stringWithFormat:@"%@(%ld)",IMTNewCarLocalizedString(@"setting_failed"),(long)error.code]];
        }
    }];
}

-(double)currentdateInterval {
    NSDate *datenow = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];
    return [timeSp doubleValue];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return IMTNewL9CarDetailSectionCount;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    //判断cell是否隐藏
    cell.hidden = ![self.sections containsObject:@(indexPath.section)];
    if (indexPath.section == IMTNewL9CarDetailSectionZeroSpeedStart) { // 零速启动
        self.zeroSpeedStartSwitch.on = self.carModel.l9_CarModel.settingParams.zero_startup;
    }else if (indexPath.section == IMTNewL9CarDetailSectionLock) { // 锁车
        self.lockCarSwitch.on = self.carModel.l9_CarModel.lockSwitch;
    }else if (indexPath.section == IMTNewL9CarDetailSectionCruiseControl) { // 自动巡航
        self.cruiseSwitch.on = self.carModel.l9_CarModel.settingParams.auto_cruise;
    }else if (indexPath.section == IMTNewL9CarDetailSectionSpeedUint) { // 速度单位
        self.speedUnitSegControl.selectedSegmentIndex = self.carModel.l9_CarModel.settingParams.speed_unit;
    }else if (indexPath.section == IMTNewL9CarDetailSectionSpeedUpIntensity) { // 加速力度
        self.speedUpSlider.value = self.carModel.l9_CarModel.settingParams.accelerate_force;
        self.speedUpValueLB.text = [NSString stringWithFormat:@"%.f",(CGFloat)self.carModel.l9_CarModel.settingParams.accelerate_force];
    }else if (indexPath.section == IMTNewL9CarDetailSectionSpeedDownIntensity){ // 刹车力度
        self.speedDownSlider.value = self.carModel.l9_CarModel.settingParams.brake_force;
        self.speedDownValueLB.text = [NSString stringWithFormat:@"%.f",(CGFloat)self.carModel.l9_CarModel.settingParams.brake_force];
    }else if (indexPath.section == IMTNewL9CarDetailSectionMaxSpeed) { // 车速限制
        self.maxSpeedSlider.value = self.carModel.l9_CarModel.settingParams.limit_speed/100;
        self.maxSpeedNumLB.text = [NSString stringWithFormat:@"%.f",(CGFloat)(self.carModel.l9_CarModel.settingParams.limit_speed/100)];
    }else if (indexPath.section == IMTNewL9CarDetailSectionL5RideModel){ // L5骑行模式
        self.l5RideModeSegControl.selectedSegmentIndex = self.carModel.l9_CarModel.settingParams.driver_mode;
        if (self.l5RideModeSegControl.selectedSegmentIndex == 0) {
            self.l5RideModeTipLB.text = IMTNewCarLocalizedString(@"prompt_l9_riding_mode_eco_tips");
        }else if (self.l5RideModeSegControl.selectedSegmentIndex == 1){
            self.l5RideModeTipLB.text = IMTNewCarLocalizedString(@"prompt_l9_riding_mode_d_tips");
        }else if (self.l5RideModeSegControl.selectedSegmentIndex == 2){
            self.l5RideModeTipLB.text = IMTNewCarLocalizedString(@"prompt_l9_riding_mode_s_tips");
        }else if (self.l5RideModeSegControl.selectedSegmentIndex == 3){
            self.l5RideModeTipLB.text = IMTNewCarLocalizedString(@"prompt_l9_riding_mode_assistance_tips");
        }
    }else if (indexPath.section == IMTNewL9CarDetailSectionRideModel){ // 骑行模式
        self.rideModeSegControl.selectedSegmentIndex = self.carModel.l9_CarModel.settingParams.driver_mode;
        if (self.rideModeSegControl.selectedSegmentIndex == 2) {
            self.speedLimitSwitch.enabled = NO;
            self.speedLimitLB.textColor = [UIColor grayColor];
        }else {
            self.speedLimitSwitch.enabled = YES;
            self.speedLimitLB.textColor = [UIColor blackColor];
        }
        if (self.rideModeSegControl.selectedSegmentIndex == 0) {
            self.rideModeTipLB.text = IMTNewCarLocalizedString(@"prompt_l9_riding_mode_eco_tips");
        }else if (self.rideModeSegControl.selectedSegmentIndex == 1){
            self.rideModeTipLB.text = IMTNewCarLocalizedString(@"prompt_l9_riding_mode_d_tips");
        }else if (self.rideModeSegControl.selectedSegmentIndex == 2){
            self.rideModeTipLB.text = IMTNewCarLocalizedString(@"prompt_l9_riding_mode_s_tips");
        }else if (self.rideModeSegControl.selectedSegmentIndex == 3){
            self.rideModeTipLB.text = IMTNewCarLocalizedString(@"prompt_l9_riding_mode_assistance_tips");
        }
    }else if (indexPath.section == IMTNewL9CarDetailSectionLight) { // 前灯
        self.lightSwitch.on = self.carModel.l9_CarModel.lightSwitch;
    }else if (indexPath.section == IMTNewL9CarDetailSectionAmbientLight) { // 氛围灯开关
        self.ambientLightSwitch.on = self.carModel.l9_CarModel.ambientLightSwitch;
    }else if (indexPath.section == IMTNewL9CarDetailSectionTurnLight) { // 转向灯开关
        self.turnLightSwitch.on = self.carModel.l9_CarModel.turnLightSwitch;
    }else if (indexPath.section == IMTNewL9CarDetailSectionTurnLight) { // 转向灯开关
        self.turnLightSwitch.on = self.carModel.l9_CarModel.turnLightSwitch;
    }else if (indexPath.section == IMTNewL9CarDetailSectionSpeedLimitSwitch) { // 限速开关
        self.speedLimitSwitch.on = self.carModel.l9_CarModel.speedLimitSwitch;
//        if (self.speedLimitSwitch.on) {
//            [self.rideModeSegControl setEnabled:NO forSegmentAtIndex:2];
//        }else {
//            [self.rideModeSegControl setEnabled:YES forSegmentAtIndex:2];
//        }
    }
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (![self.sections containsObject:@(section)]) {
        return nil;
    }
    if (section == IMTNewL9CarDetailSectionSpeedUint) { // 速度单位
        return IMTNewCarLocalizedString(@"car_feature_metric");
    }else if (section == IMTNewL9CarDetailSectionSpeedUpIntensity) { // 加速力度
        return @"加速度力度";
    }else if (section == IMTNewL9CarDetailSectionSpeedDownIntensity){ // 刹车力度
        return @"刹车力度";
    }else if (section == IMTNewL9CarDetailSectionRideModel || section == IMTNewL9CarDetailSectionL5RideModel){ // 骑行模式
        return IMTNewCarLocalizedString(@"car_feature_riding_mode");
    }else if (section == IMTNewL9CarDetailSectionSpeedLimitSwitch) {
        return IMTNewCarLocalizedString(@"allow_bigger_speed_limit");
    }
    return nil;
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    if (![self.sections containsObject:@(section)]) {
        return nil;
    }else if (section == IMTNewL9CarDetailSectionSpeedLimitSwitch) {
        if (self.carModel.l9_CarModel.settingParams.driver_mode == L9_CarModelRideModelSport) {
            return [NSString stringWithFormat:@"%@%@",IMTNewCarLocalizedString(@"prompt_allow_bigger_speed_limit_desc"),IMTNewCarLocalizedString(@"prompt_switch_to_other_ride_mode_to_enable")];
        }
        if (!self.carModel.l9_CarModel.speedLimitSwitch) {
            return IMTNewCarLocalizedString(@"prompt_allow_bigger_speed_limit_desc");
        }else {
            return IMTNewCarLocalizedString(@"prompt_disallow_bigger_speed_limit_desc");
        }
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.sections containsObject:@(indexPath.section)]) {
        if (indexPath.section == IMTNewL9CarDetailSectionRideModel || indexPath.section == IMTNewL9CarDetailSectionL5RideModel){ // 骑行模式
            return 100;
        }
        return 50;
    }
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if ([self.sections containsObject:@(section)]) {
        return [super tableView:tableView heightForHeaderInSection:section];
    }
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if ([self.sections containsObject:@(section)]) {
        if (section == IMTNewL9CarDetailSectionSpeedLimitSwitch) {
            return [super tableView:tableView heightForFooterInSection:section];
        }
        return 10;
    }
    return CGFLOAT_MIN;
}

#pragma mark - TableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"==========================");
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if ([KSBLEManager sharedManager].state != KSBLEManagerStateSubscribed) {
        [self showErrorHUDWithText:IMTLocalizedStringFromTable(@"Connected to the vehicle to set", @"Car", @"连接车辆才能设置")];
        return;
    }
    
    if (indexPath.section == IMTNewL9CarDetailSectionSearch) {
        if (self.carModel.l9_CarModel.LX_CarType >= 0) {
            [KSBLEManager.sharedManager disconnect];
        }
        IMTCarManager.sharedCarManager.currentCar = nil;
        [self dismissViewControllerAnimated:true completion:nil];
        
    }else if(indexPath.section == IMTNewL9CarDetailSectionFirmwareUpdate){ // 固件升级
        NewFirmwareUpdateViewController *firmwareUpate = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"NewFirmwareUpdateViewController"];
        firmwareUpate.carModel = self.carModel;
        [self.navigationController pushViewController:firmwareUpate animated:YES];
    }else if (indexPath.section == IMTNewL9CarDetailSectionCalibration) { // 车身校正
        L9CorrectionViewController *vc = [[L9CorrectionViewController alloc] init];
        vc.l9CarModel = self.carModel.l9_CarModel;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.section == IMTNewL9CarDetailSectionRidingAssistance) { // 骑行辅助
        RidingAssistanceViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"RidingAssistanceViewController"];
        vc.l9Carmodel = self.carModel.l9_CarModel;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.section == IMTNewL9CarDetailSectionAboutCar) { // 关于车辆
        IMTAboutCarViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"IMTAboutCarViewController"];
        vc.carModel = self.carModel;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.section == IMTNewL9CarDetailSectionDiagnose) { // 故障检测
        DetectionViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"DetectionViewController"];
        vc.carModel = self.carModel;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.section == IMTNewL9CarDetailSectionCarPassword) { // 蓝牙密码
        [self checkCarIsHasPassword:^(BOOL ishas) {
            if (ishas) {
                LXCarBlePasswordViewController *vc = [[LXCarBlePasswordViewController alloc] initWithNibName:@"LXCarBlePasswordViewController" bundle:nil];
                vc.carModel = self.carModel.l9_CarModel;
                [self.navigationController pushViewController:vc animated:YES];
            }else {
                // 提示输入密码
                NSLog(@"==============还未设置车辆密码！");
                [self showInputPasswordWithType:1 isLock:0];
            }
        }];
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    return NO;
}

@end
